<template>
  <Form
    class="xtx-form"
    :validation-schema="formschema"
    v-slot="{ errors }"
    ref="formCom"
  >
    <div class="user-info">
      <img :src="avater" alt="" />
      <p>Hi，{{ nickname }} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field
          name="mobile"
          class="input"
          :class="{ err: errors.mobile }"
          type="text"
          placeholder="绑定的手机号"
          v-model="form.mobile"
        />
      </div>
      <div class="error" v-if="errors.mobile">{{ errors.mobile }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field
          name="code"
          class="input"
          :class="{ err: errors.code }"
          type="text"
          placeholder="短信验证码"
          v-model="form.code"
        />
        <span class="code" @click="send()">{{
          time === 0 ? '发送验证码' : `${time}秒后发送`
        }}</span>
      </div>
      <div class="error" v-if="errors.code">{{ errors.code }}</div>
    </div>
    <a href="javascript:;" class="submit" @click="submit()">立即绑定</a>
  </Form>
</template>

<script>
import { Form, Field } from 'vee-validate'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import schema from '@/utils/vee-validate-schema'
import { reactive, ref, onUnmounted, getCurrentInstance } from 'vue'
import { userQQBindCode, userQQBindLogin } from '@/apis/user'
import QC from 'qc'
export default {
  name: 'CallbackBind',
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  components: { Form, Field },
  setup (props) {
    // 用户信息
    const nickname = ref('')
    const avater = ref('')
    // 获取用户信息
    if (QC.Login.check()) {
      QC.api('get_user_info').success((res) => {
        avater.value = res.data.figureurl_1
        nickname.value = res.data.nickname
      })
    }
    // 表单对象
    const form = reactive({
      mobile: '',
      code: ''
    })
    // 验证规则
    const formschema = {
      mobile: schema.mobile,
      code: schema.code
    }

    // 发送验证码
    let timer = null
    const time = ref(0)
    const formCom = ref(null)
    const { proxy } = getCurrentInstance()
    onUnmounted(() => {
      clearInterval(timer)
    })
    const send = async () => {
      const ismobile = schema.mobile(form.mobile)
      try {
        if (ismobile === true) {
          if (time.value === 0) {
            await userQQBindCode(form.mobile)
            // await userQQBindCode(form.mobile)
            proxy.$message({ type: 'success', text: '发送成功' })
            time.value = 60
            timer = setInterval(() => {
              time.value--
              if (time.value <= 0) {
                clearInterval(timer)
              }
            }, 1000)
          }
        } else {
          formCom.value.setFieldError('mobile', ismobile)
        }
      } catch (e) {
        proxy.$message({
          type: 'error',
          text: e.response.data.message || '此手机号未注册'
        })
      }
    }

    // 绑定手机号
    const store = useStore()
    const router = useRouter()
    const submit = () => {
      if (formCom.value.validate) {
        userQQBindLogin({ unionId: props.unionId, ...form })
          .then((res) => {
            const { id, account, avatar, mobile, nickname, token } = res.result
            store.commit('user/setUser', {
              id,
              account,
              avatar,
              mobile,
              nickname,
              token
            })
            store.dispatch('cart/mergeCart').then(() => {
              router.push(store.state.user.redirectpath)
              proxy.$message({ type: 'success', text: '绑定账号成功' })
            })
          })
          .catch((e) => {
            proxy.$message({ type: 'error', text: '验证码错误' })
          })
      }
    }
    return { nickname, avater, form, formschema, send, time, formCom, submit }
  }
}
</script>

<style scoped lang="less">
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;
  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }
  p {
    padding-left: 10px;
  }
}
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
